Ext.define('DragonApp.view.notice.Controller', {

    extend: 'DragonApp.view.foundation.ViewController',
    alias: 'controller.notice',

    config: {
        channellist: Ext.create('DragonApp.store.Channel', {})
    },
    //==================
    //添加文字、图像公告
    //==================
    onAddTxt: function(button, e, options) {
        this.createTxtDialog(null);
    },

    onAddImage: function(button, e, options) {
        this.createImageDialog(null);
    },
    //========
    //编辑记录
    //========
    onEdit: function(button) {
        var record = button.getWidgetRecord();

        //公告类型区分
        switch (record.getData().type) {
            case '文字':
                this.createTxtDialog(record);
                break;
            case '图像':
                this.createImageDialog(record);
                break;
        }
    },

    //============
    //创建文字公告
    //============
    createTxtDialog: function(record) {

        var me = this,
            view = me.getView();

        me.dialog = view.add({
            xtype: 'notice_txt_window',
            height: 440,
            width: 900,
            viewModel: {
                data: {
                    title: record ? '编辑公告' : '新增公告'
                }
            }
        });
        if (!Ext.isEmpty(record)) {
            me.dialog.down("form").loadRecord(record);
        }
        //========
        //表单类型
        //========
        var formTypeField = Ext.ComponentQuery.query('hiddenfield#formtype')[0];
        var channelField = Ext.ComponentQuery.query('notice_txt_window multichannelcombo')[0];
        var txtResetBtn = Ext.ComponentQuery.query('button#txtResetBtn')[0];

        txtResetBtn.setHidden(true);

        // 编辑公告
        if (!Ext.isEmpty(record)) {

            //加载数据
            me.dialog.down("form").loadRecord(record);

            //禁止编辑
            channelField.on('beforequery', function() {
                return false;
            });

            //渠道只读
            channelField.setReadOnly(true);
            formTypeField.setValue('edit');

        } else {
            formTypeField.setValue('new');
        }
        me.dialog.show();
    },

    //============
    //创建图片公告
    //============
    createImageDialog: function(record) {

        var me = this,
            view = me.getView();

        me.dialog = view.add({
            xtype: 'notice-image-window',
            height: 485,
            width: 1160,
            title: record ? '编辑公告' : '新增公告'
        });

        //编辑公告
        var formTypeField = Ext.ComponentQuery.query('hiddenfield#formtype')[0];

        if (!Ext.isEmpty(record)) {

            me.dialog.down("form").loadRecord(record);
            var channelField = Ext.ComponentQuery.query('multichannelcombo')[0];
            //只读约束
            channelField.setReadOnly(true);
            channelField.on('beforequery', function() {
                return false;
            });

            var pictures = record.get('pictures');
            var arr = pictures.split(",");

            var imgStore = Ext.data.StoreManager.lookup('imageNoticeStore');
            var selectedStore = Ext.data.StoreManager.lookup('selectedStore');
            var imgResetBtn = Ext.ComponentQuery.query('button#imgResetBtn')[0];

            imgResetBtn.setHidden(true);

            if (arr.length > 0) {

                var pics = [];

                //找到图库当中和公告图像字段匹配的记录

                imgStore.load({
                    scope: this,
                    callback: function(records, operation, success) {
                        for (var j = 0; j < arr.length; j++) {

                            for (var i = 0; i < records.length; i++) {
                                if (arr[j] == records[i].get('filename')) {
                                    var cloneRecord = imgStore.getAt(i).copy();
                                    pics.push(cloneRecord);
                                }
                            }
                        }
                        //添加记录
                        selectedStore.add(pics);

                        //表单类型字段赋值
                        formTypeField.setValue('edit');

                        //显示窗体
                        me.dialog.show();
                    }
                });
            }
        } else {
            formTypeField.setValue('new');
            me.dialog.show();
        }
    },

    //========
    //提交公告
    //========
    onSave: function(button, e, options) {

        //表单验证
        var window = button.up('window');
        var form = window.down('form').getForm();

        if (!form.isValid()) return;

        //表单取值
        var formValue = form.getValues();

        formValue.channels = formValue.channel.toString();

        //网址提交
        var url = ('new' == formValue.formtype) ? '/index/Notice/add/' : '/index/Notice/update/';
        url = DragonApp.ux.config.Config.getUrl(url);

        var grid = Ext.ComponentQuery.query('noticegrid')[0];
        var store = grid.getStore();

        window.mask('提交中...');

        Ext.data.JsonP.request({
            url: url,
            async: false,
            params: formValue,
            callbackKey: "callback",
            success: function(result) {

                window.unmask();
                DragonApp.util.Msg.showToast(result.msg);

                switch (result.success) {
                    case true:
                        form.destroy();
                        window.destroy();
                        store.load();
                        break;
                }
            },
            failure: function(result) {
                window.unmask();
                DragonApp.util.Msg.showToast(result);
            }
        });
    },

    //==========
    //单记录删除
    //==========
    onDelete: function(button, e, options) {

        //当前记录
        var record = button.getWidgetRecord();
        var param = { id: record.get('id') };
        var url = DragonApp.ux.config.Config.getUrl('/index/Notice/delete/');

        //删除请求
        this.deletePrompt(url, param, record);

    },

    //========
    //批量删除
    //========
    onBatDelete: function() {

        var grid = this.getView();
        var url = DragonApp.ux.config.Config.getUrl('/index/Notice/batDelete/');

        this.onBatDeleteExec(grid,url);
    },

    //========
    //回车搜索
    //========
    onTextFieldSpecialKeySearch: function(field, e, options) {
        if (e.getKey() === e.ENTER) {
            this.onSearch();
        }
    },

    //==========
    //工具栏搜索
    //==========
    onSearch: function() {

        //搜索字段
        var searchFilter = Ext.ComponentQuery.query('notice-bar')[0];
        var searchField = searchFilter.queryById('search_field');

        //复位
        var store = Ext.data.StoreManager.lookup('jsonPNoticeStore');
        store.clearFilter();

        var key = searchField.getValue();

        if ('有效' == key || '失效' == key) {

            //有效类型过滤
            store.filterBy(function(item) {
                var begintime = Date.parse(item.get("begintime"));
                var endtime = Date.parse(item.get("endtime"));
                var nowtime = Date.parse(new Date());
                if (nowtime >= begintime && nowtime <= endtime) {
                    return '有效' == key ? true : false;
                } else {
                    return '有效' == key ? false : true;
                }
            });

        } else {
            //文字公告标题及内容过滤
            store.filterBy(function(item) {
                if (0 == item.get("type")) {
                    return (item.get('title').indexOf(searchField.getValue()) >= 0 || item.get('content').indexOf(searchField.getValue()) >= 0);
                } else if ("" == searchField.getValue()) {
                    return true;
                } else {
                    return false;
                }
            });
        }
    },
    //========
    //回车搜索
    //========
    onTextFieldSpecialKey: function(field, e, options) {
        if (e.getKey() === e.ENTER) {
            this.onSubmitClick();
        }
    },
    //========
    //查询公告
    //========
    onSubmitClick: function(button, e, options) {
        var me = this;
        var form = this.getView().getForm();

        if (!form.isValid()) return;

        var formValue = form.getValues();

        var grid = Ext.ComponentQuery.query('noticegrid')[0];
        var store = grid.getStore();

        store.load({
            params: formValue,
            scope: this,
            callback: function(records, operation, success) {
                if (success == false) {
                    store.removeAll();
                }
            }
        });
    },

    //========
    //图像预览
    //========
    onPreview: function(button, e, options) {

        //当前记录
        var record = button.getWidgetRecord();
        var path = record.get('path');
        var me = this,
            view = me.getView();

        me.dialog = view.add({
            xtype: 'window',
            title: record.get('filename') + ' 预览',
            width: record.get('width') + 2,
            height: record.get('height') + 37,
            layout: 'fit',
            html: '<img src="' + DragonApp.ux.config.Config.getTagUrl(record.get('filename')) + '" alt="' + record.get('filename') + '" />'
        });

        me.dialog.show();
    },
    //============
    //内容提示渲染
    //============
    attrRender: function(value, metadata, record, rowIndex, columnIndex, store) {

        if (typeof(value) == "undefined") {
            value = '';
            metadata.tdAttr = 'data-qtip="' + value + '" ' + 'data-qalign="bl-br"' + 'data-qwidth="auto"';
            return value;
        } else {
            metadata.tdAttr = 'data-qtip="' + value + '" ' + 'data-qalign="bl-br"' + 'data-qwidth="auto"';
            return value;
        }
    },

    //========
    //渠道渲染
    //========
    channelRender: function(value) {

        var store = this.getChannellist();

        //遍历store
        for (var i = 0; i < store.getCount(); i++) {

            var record = store.getAt(i);
            if (value == record.get('cid')) {
                return record.get('cname');
            }
        }
        return value;
    },

    //============
    //状态提示渲染
    //============
    statusRender: function(value, metadata, record, rowIndex, columnIndex, store) {

        var begintime = Date.parse(record.get("begintime"));
        var endtime = Date.parse(record.get("endtime"));
        var nowtime = Date.parse(new Date());
        if (nowtime >= begintime && nowtime <= endtime) {
            return '有效';
        } else {
            return '失效';
        }
    }
});